package dk.snaveponyklub.servlets;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import dk.snaveponyklub.handler.HandlerFactory;
import dk.snaveponyklub.util.Logger;
import dk.snaveponyklub.xml.LoadXML;
import dk.snaveponyklub.xsd.Userlogin;

public class LoginFilter implements Filter {

	private ServletContext context;
	
	private LoadXML aLoadXML;

	public LoginFilter() {
	    aLoadXML = new LoadXML();
	}

	public void init(FilterConfig c) throws ServletException {
		context = c.getServletContext();
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hreq = (HttpServletRequest) request;
		HttpServletResponse hresp = (HttpServletResponse) response;

		// Is the user trying to login? using af post
		if (hreq.getMethod().equals("POST") || hreq.getMethod().equals("PUT")) {
		    boolean userlogin = false;
		    String user = null;
            String pass = null;
            
		    String requestUrl = hreq.getRequestURL().toString();
		    
		    if(requestUrl.contains("login")) {
		        userlogin = true;
		        Userlogin login = aLoadXML.load(request.getInputStream());
		        if(login != null) { 
    		        user = login.getLogin().getUsername();
    		        pass = login.getLogin().getPassword();	
    		        //context.log("login user: " + user + " pass: " + pass);	
		        }
		        else {
		            hresp.sendError(HttpServletResponse.SC_BAD_REQUEST, aLoadXML.getLastError());
		        }
		    }	
			/*
			Map param = hreq.getParameterMap();
			if(param.containsKey("user") && param.containsKey("password")) {
				 user = ((String[]) param.get("user"))[0];
				 pass = ((String[]) param.get("password"))[0];
			}
			*/
		    
			HttpSession session = hreq.getSession();
			
			
			if (user != null && pass != null) {
				// user is ok
			    String returnValue = verifyUser(user, pass, hresp);
				if (returnValue != null) {
					try {
						session.setAttribute("LoggedIn", Boolean.TRUE);	
						hresp.getWriter().println(returnValue);
					} catch (Exception e) {
						hresp.sendError(HttpServletResponse.SC_BAD_REQUEST,"malformed request");
					}
				} 
				else {
					try {
						session.setAttribute("LoggedIn", Boolean.FALSE);
					}
					catch (Exception e) {
						hresp.sendError(HttpServletResponse.SC_BAD_REQUEST,"malformed request");
					}
				}
			}
			
			Object pUser = session.getAttribute("LoggedIn");
			if (pUser == null) {
			    hresp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Login failed, puser = null");				
			} else {
				if (((Boolean) pUser).booleanValue() ){
				    if(userlogin) {				            
				        //hresp.getWriter().println("Login" + true);
				    }
				    else {
				        chain.doFilter(hreq, hresp);
				    }
				} else {
					hresp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Login failed");
					//hresp.getWriter().println("Login failed" + pUser.toString());
				}
			}
		}
		else if(hreq.getMethod().equals("DELETE")){
		    String requestUrl = hreq.getRequestURL().toString();
            
            if(requestUrl.contains("logout")) {
    			HttpSession session = hreq.getSession();
    			if(session != null)
    			{
    				session.invalidate();
    			}
            }
		}
		else {
			chain.doFilter(hreq, hresp);
		}
	}

	private String verifyUser(String username, String password, HttpServletResponse hresp) {
	    String ret = null;
	    
	    try {
            String xml = HandlerFactory.getInstance().validateLogin(username, password);
            
            ret = xml;           
        } catch (Throwable e) {
            try {
                hresp.sendError(HttpServletResponse.SC_BAD_REQUEST,"malformed request");
            } catch (IOException e1) {
                Logger.error("" + e1);
            }
        }
        
		return ret;
	}
}
